package com.st.emps.project.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.st.emps.project.model.ProjectModel;
import com.st.emps.util.JDBCUtil;

public class ProjectDao {

	
	public int insert(ProjectModel model) {
		String sql = "insert into project(code,name) values(?,?)";
		return JDBCUtil.update(sql,model.getCode(),model.getName());
	}
	public int delete(ProjectModel model) {
	    String sql = "delete from project where code =?";
	    return JDBCUtil.update(sql,model.getCode());

	}
	public int update(ProjectModel model) {
		String sql = "update project set name = ? where code= ?";
        return JDBCUtil.update(sql, model.getName(),model.getCode());
	}
	public List<ProjectModel> select(ProjectModel model) {
		StringBuffer sql = new StringBuffer("select code,name,department_code,(select name from department where department_code=department.code)department_name from project where 1=1 ");
        List<Object> vals = appendWhere(sql,model);
        Map<String,String> fields = new HashMap<String,String>();
        fields.put("code", "code");
        fields.put("name", "name");
        fields.put("departmentCode", "department_code");
        fields.put("departmentName", "department_name");
        return JDBCUtil.query(sql,vals,ProjectModel.class,fields);
	}
	private List<Object> appendWhere(StringBuffer sql,ProjectModel model) {
		List<Object> list = new ArrayList<Object>();
		String code = model.getCode();
		if(code!=null&&!code.trim().isEmpty()) {
			sql.append(" and code like ? ");
			list.add(code);
		}
		String name = model.getName();
		if(name!=null&&!name.trim().isEmpty()) {
			sql.append(" and name like ? ");
			list.add(name);
		}
		if(model.isPageOn()) {
			sql.append(" limit ?,? ");
			list.add(model.getRowStart());
			list.add(model.getPageLimit());
		}
		return list;
	}
	public Object selectCount(ProjectModel model) {
		StringBuffer sql = new StringBuffer("select count(1) from project where 1=1 ");
		List<Object> list = appendWhere(sql,model);
		return JDBCUtil.queryInt(sql,list);
	}
	public int updateDepart(ProjectModel model) {
		String sql = "update project set department_code = ? where code = ? ";
		return JDBCUtil.update(sql, model.getDepartmentCode(),model.getCode());
	}

}